package com.yj.spider.RegCenter;

import org.apache.commons.lang3.StringUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * Created by 刘治军 on 2017/10/15.
 * 爬虫注册中心（zookeeper实现）
 */
public class SpiderRegCenter {
    public String NAME_SPACE;
    public String SPIDER_DIR;
    private CuratorFramework curatorFrameworkClient;

    /**
     * 构造spider 注册中心
     *
     * @param nameSpace
     * @param spiderDir
     */
    public SpiderRegCenter(String nameSpace, String spiderDir, String connectionInfo) {
        this.NAME_SPACE = nameSpace;
        this.SPIDER_DIR = spiderDir;
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        curatorFrameworkClient = CuratorFrameworkFactory.builder()
                .connectionTimeoutMs(5000)
                .sessionTimeoutMs(10000)
                .connectString(connectionInfo)
                .namespace(nameSpace)
                .retryPolicy(retryPolicy).build();
        curatorFrameworkClient.start();
    }

    /**
     * 关闭客户端链接
     */
    public void close() {
        if (curatorFrameworkClient != null)
            curatorFrameworkClient.close();
    }

    /**
     * 创建临时节点
     * @param path
     * @param data
     * @throws Exception
     */
    public void createPath(String path, String data) throws Exception {
        if (StringUtils.isNotBlank(data))
            curatorFrameworkClient.create().withMode(CreateMode.EPHEMERAL).forPath(path, data.getBytes());
        else
            curatorFrameworkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path);
    }

    /**
     * 删除节点
     * @param path
     * @throws Exception
     */
    public void deletePath(String path) throws Exception {
            curatorFrameworkClient.delete().guaranteed().deletingChildrenIfNeeded().forPath(path);
    }

    /**
     * 获取路径数据
     * @param path
     * @throws Exception
     */
    public void getData(String path) throws Exception{
        Stat stat = new Stat();
        curatorFrameworkClient.getData().storingStatIn(stat).forPath(path);
    }

    /**
     * 更新数据
     * @param path
     * @param data
     * @throws Exception
     */
    public void setData(String path,String data) throws  Exception{
        curatorFrameworkClient.setData().forPath(path,data.getBytes());
    }
}
